<template>
  <div>
    <!-- 
      注册页面组件
      功能：提供手机号注册和账号注册两种方式的表单界面，通过 tab 切换不同注册方式
    -->
    <div class="wrap">
      <div class="container">
        <div class="reg-box">
          <div class="reg-box-wrap">
            <!-- 注册标题 -->
            <h2 class="title">注册账号</h2>

            <!-- 注册方式切换 tabs -->
            <div class="reg-tabs">
              <!-- 手机号注册 tab -->
              <div
                :class="num == 1 ? 'active' : ''"
                @click="setNum(1)"
                class="reg-tabs-item"
                style="margin-right: 40px"
              >
                手机号注册
              </div>

              <!-- 账号注册 tab -->
              <div
                :class="num == 2 ? 'active' : ''"
                @click="setNum(2)"
                class="reg-tabs-item"
              >
                账号注册
              </div>
            </div>

            <!-- 注册表单区域 -->
            <div class="reg-form-warp" style="min-width: 360px">
              <!-- 手机号注册表单 -->
              <DynamicForm
                :loading="isLoading"
                ref="ruleFormRef"
                v-if="num === 1"
                :flagNum="1"
                :formData="ruleForm"
                :fields="phoneFields"
                :rules="rules"
                :path="path"
                :submit-disabled="disableSubmitBtn"
                class="reg-form"
                @submit="handleSubmitWithPhone"
              ></DynamicForm>

              <!-- 账号注册表单 -->
              <DynamicForm
                :loading="isLoading"
                v-if="num === 2"
                :flagNum="2"
                :formData="ruleForm"
                :rules="rules"
                :path="path"
                :submit-disabled="disableSubmitBtn"
                :fields="accountFields"
                class="reg-form"
                @submit="handleSubmitWithAccount"
              ></DynamicForm>
            </div>

            <!-- 登录提示信息 -->
            <div class="reg-tips">
              已有账号？
              <span class="login-btn" style="color: #dd3a5f; cursor: pointer">
                登录
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 注册成功对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="注册成功"
      width="500px"
      :show-close="false"
      center
    >
      <div class="dialog-content">
        <div class="success-icon">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="48"
            height="48"
            viewBox="0 0 24 24"
            fill="none"
            stroke="#67c23a"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
          >
            <circle cx="12" cy="12" r="10"></circle>
            <path d="m9 12 2 2 4-4"></path>
          </svg>
        </div>
        <div class="success-message">
          <h3>恭喜您注册成功！</h3>
          <p>请选择下一步操作</p>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="success"
            @click="handleDialogAction('profile', currentToken)"
          >
            跳转个人页面
          </el-button>
          <el-button
            type="primary"
            @click="handleDialogAction('course', currentToken)"
          >
            跳转课程首页
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { User, Lock, Iphone, Cellphone, Loading } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import DynamicForm from '@/components/common/DynamicForm.vue'
import { useRoute } from 'vue-router'
import { encrypt } from '@/utils/aes'
import { registerByPhone, registerByUser } from '@/api/register'
import { ElNotification } from 'element-plus'
import router from '@/router'
import useUserStore from '@/store/modules/user'

//按钮是否加载中
// 添加loading状态变量
const isLoading = ref(false)
// 定义一个响应式数据 dialogVisible，用于控制对话框的显示状态
// 默认值为 false，表示对话框初始状态为隐藏
const dialogVisible = ref(false)
// 存储当前token
const currentToken = ref('')
// 控制提交按钮禁用状态
const disableSubmitBtn = ref(false)

let route = useRoute()
let path = route.path as string
/**
 * 创建一个响应式的表单引用对象
 * 用于获取和操作DOM元素或组件实例
 *
 * @type {Object} - 返回一个包含value属性的响应式引用对象
 * @property {any} value - 初始值为undefined，可以用来存储DOM引用或组件实例
 */
let ruleFormRef = ref()
//默认为1，表示手机注册
let num = ref(1)

// 代码优化，num 的值只允许为 1 或 2，但代码中没有对非法值进行处理
const setNum = (value: number) => {
  if ([1, 2].includes(value)) {
    num.value = value
    // 重置表单引用，确保重新创建时能正确计算宽度
    ruleFormRef.value = null
  } else {
    console.error('非法的 num 值:', value)
  }
}

//表单数据ts类型
interface RuleForm {
  phone: string
  password: string
  accountName: string
  verificationCode: string
}

// 表单数据
const ruleForm = reactive<RuleForm>({
  phone: '', // 手机号
  password: '', // 密码
  accountName: '', // 账号名称
  verificationCode: '' // 验证码
})

// 字段配置
// phoneFields: Array<any>
const phoneFields = [
  { prop: 'phone', placeholder: '(+86) 请输入手机号码', icon: Iphone },
  {
    prop: 'verificationCode',
    placeholder: '请输入验证码',
    icon: Cellphone,
    getCode: () => console.log('发送验证码')
  }
]

// 账号注册表单配置
const accountFields = [
  { prop: 'accountName', placeholder: '请输入账号名称', icon: User },
  {
    prop: 'password',
    placeholder: '请输入密码',
    icon: Lock,
    type: 'password',
    showPassword: true
  },
  { prop: 'phone', placeholder: '请输入手机号', icon: Iphone },
  {
    prop: 'verificationCode',
    placeholder: '请输入验证码',
    icon: Cellphone,
    getCode: () => console.log('发送验证码')
  }
]

// 表单验证规则
const rules = reactive({
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6到20位之间', trigger: 'blur' }
  ],
  accountName: [
    { required: true, message: '请输入账号名称', trigger: 'blur' },
    { min: 3, max: 20, message: '账号名称长度应在3到20位之间', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{4}$/, message: '验证码应为4位数字', trigger: 'blur' }
  ]
})

// 将handleDialogAction移到全局作用域

/**
 * 处理对话框操作的函数
 * @param action - 操作类型，'course'表示跳转到课程首页，'profile'表示跳转到个人页面
 * @param token - 用户登录所需的token
 */
const handleDialogAction = async (
  action: 'course' | 'profile',
  token: string
) => {
  dialogVisible.value = false
  try {
    // 先登录
    console.log('开始登录...')
    const loginRes = await useUserStore().userLogin(token)
    console.log('登录成功:', loginRes)

    // 根据选择的操作跳转不同页面
    let redirectPath = ''
    let successMessage = ''

    if (action === 'course') {
      redirectPath = '/'
      successMessage = '已成功跳转至课程首页'
    } else if (action === 'profile') {
      redirectPath = '/geren'
      successMessage = '已成功跳转至个人页面'
    }

    // 执行跳转
    try {
      await router.push(redirectPath)
      ElNotification.success({
        title: '登录成功!',
        message: successMessage
      })
    } catch (error) {
      console.error('页面跳转失败:', error)
      ElNotification.error({
        title: '跳转失败',
        message: '无法跳转到目标页面，请稍后刷新重试'
      })
    }
  } catch (loginError) {
    console.error('登录失败:', loginError)
    ElNotification.error({
      type: 'error',
      title: '登录失败',
      message: (loginError as Error).message || '登录失败，请稍后重试'
    })
  }
}
// 提交表单数据
const handleSubmitWithPhone = async (formData: any) => {
  isLoading.value = true
  disableSubmitBtn.value = true
  try {
    // 加密敏感数据
    const encryptedPhone = encrypt(formData.phone)
    const encryptedVerificationCode = encrypt(formData.verificationCode)

    // 调用注册接口
    const registerRes = await registerByPhone({
      phone: encryptedPhone,
      verificationCode: encryptedVerificationCode
    })

    // 检查注册结果
    if (registerRes && (registerRes as any).token) {
      const token = (registerRes as any).token
      console.log('注册成功，获取到token:', token)

      // 注册成功后显示对话框
      dialogVisible.value = true
      // 存储token供对话框使用
      currentToken.value = token
    } else {
      throw new Error('注册失败，未获取到token')
    }
  } catch (error: any) {
    console.error('注册失败:', error)
    ElNotification.error({
      type: 'error',
      title: '注册失败!',
      message: error.msg || error.message || '注册失败，请检查输入!'
    })
  } finally {
    // 无论成功失败，都重置loading状态
    isLoading.value = false
    disableSubmitBtn.value = false
  }
}

// 提交表单数据
const handleSubmitWithAccount = async (formData: any) => {
  isLoading.value = true
  disableSubmitBtn.value = true
  console.log('传递给父组件的数据', formData)

  // load.value = true
  // console.log('提交表单数据:', ruleForm)

  console.log('formData.accountName', encrypt(formData.accountName))
  console.log('formData.password', encrypt(formData.password))
  try {
    // const res = await loginByJson({
    //   username: encrypt(formData.accountName),
    //   password: encrypt(formData.password)
    // })
    //  console.log('登录返回的数据', res)

    const res = await registerByUser({
      username: encrypt(formData.accountName),
      phone: encrypt(formData.phone),
      password: encrypt(formData.password)
    })

    console.log('登录返回的数据', res)
  } catch (error) {
    console.error('登录失败', error)
  } finally {
    isLoading.value = false
    disableSubmitBtn.value = false
  }
}
</script>
<style scoped>
.dialog-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.success-icon {
  margin-bottom: 20px;
}

.success-message {
  text-align: center;
  margin-bottom: 20px;
}

.success-message h3 {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}

.success-message p {
  font-size: 14px;
  color: #666;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
}
</style>

<style scoped lang="less">
.wrap {
  min-width: 600px;
  height: 100vh;
  min-height: 929px;
  background: #f7fafe;
  position: relative;
  display: flex;
  overflow-y: auto;
  .container {
    height: 100%;
    flex: 1;
    position: relative;
    background-image: url(//res.orayimg.com/oray-login/1.0/img/login-bg.9c3e2f2.jpg);
    background-repeat: no-repeat;
    background-position: 50%;
    background-size: contain;
    background-color: #f7fbff;
    .reg-box {
      border: 2px solid #fff;
      background: hsla(0, 0%, 100%, 0.6);
      border-radius: 8px;
      box-shadow: 0 4px 50px rgba(87, 126, 255, 0.04);
      backdrop-filter: blur(10px);
      min-width: 440px;
      position: absolute;
      top: calc(40% - 278.4px);
      left: 50%;
      transform: translateX(-50%);
      .reg-box-wrap {
        position: relative;
        padding: 60px 40px 0;
        .title {
          font-size: 24px;
          line-height: 32px;
          color: #1d2129;
          font-weight: 550;
        }
        .reg-tabs {
          margin-top: 32px;
          display: flex;
          color: #1d2129;
          .reg-tabs-item {
            cursor: pointer;
            padding-bottom: 8px;
            border-bottom: 2px solid transparent;
            font-size: 16px;
            line-height: 21px;
            &.active {
              color: #3773f5;
              border-bottom-color: #3773f5;
              font-weight: 550;
            }
          }
        }
        .reg-form-warp {
          margin-top: 24px;
          width: 100%; /* 确保容器宽度为100% */
        }
        .reg-form {
          width: 100%; /* 确保表单宽度为100% */
        }
        .reg-tips {
          padding-bottom: 58px;
          display: flex;
          flex-direction: row;
          justify-content: end;
        }
      }
    }
  }
}
</style>
